package sk.stuba.fiit.ltasys.web.mvc.model.service.impl;

import java.math.BigInteger;
import java.security.cert.X509CRL;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sk.stuba.fiit.ltasys.web.mvc.model.dao.CrlAndCertDao;
import sk.stuba.fiit.ltasys.web.mvc.model.entity.CrlEntity;
import sk.stuba.fiit.ltasys.web.mvc.model.service.CommunicatorService;
import sk.stuba.fiit.ltasys.web.mvc.model.service.CrlService;

@Service("crlService")
public class CrlServiceImpl implements CrlService {

	@Autowired
	CrlAndCertDao crlAndCertDao;
	@Autowired
	CommunicatorService communicatorService;

	public void saveCrl(CrlEntity crl) {
		crlAndCertDao.saveCrl(crl);
	}
	
	public CrlEntity getCrlByIssuerAndSerialNumber(String issuer,
			BigInteger serialNum) {
		return crlAndCertDao.getActualCrl(issuer, serialNum);
	}
	
	public void deleteCrl(CrlEntity crl) {
		crlAndCertDao.deleteCrl(crl);
		
	}

	public CrlEntity handleCrls(HashSet certificates) throws Exception {
		CrlEntity result =  crlAndCertDao.getActualCrl(null, null);
		Date actualdate = new Date();
		if(result.getCrl_id() == null || actualdate.after(result.getNextUpdate())){
			X509CRL crl = communicatorService.getCRLFromPKIByIssuer(null);
			result.convertFtomX09CRL(crl);
			saveCrl(result);
			return result;
		}

		return result;
	}

	public boolean downloadNewCrl() throws Exception {
		CrlEntity result =  crlAndCertDao.getActualCrl(null, null);	
		X509CRL crl = communicatorService.getCRLFromPKIByIssuer(null);
		CrlEntity newCrl = new CrlEntity();
		newCrl.convertFtomX09CRL(crl);
		if(!result.equals(newCrl)){
			saveCrl(newCrl);
			return true;
		}
		return false;
	}
	
	
}
